/**
 * useViewport Composable
 * 
 * 用于管理 Cornerstone3D 视口的 Vue 组合式函数
 * 
 * @author yangzhixin
 * @module composables/useViewport
 */

import { ref, computed, watch, type Ref } from 'vue';
import type { CornerstoneFacade, ViewportType } from 'js-3d-model';

/**
 * 视口配置接口
 */
export interface ViewportConfig {
  /** 视口类型 */
  type: ViewportType;
  /** 视口ID */
  viewportId?: string;
  /** 背景颜色 */
  background?: [number, number, number];
  /** 初始方向 */
  orientation?: string;
}

/**
 * 图像加载选项
 */
export interface ImageLoadOptions {
  /** 图像ID数组 */
  imageIds: string[];
  /** 当前索引 */
  currentIndex?: number;
  /** 是否预加载 */
  preload?: boolean;
}

/**
 * 窗宽窗位设置
 */
export interface WindowLevelSettings {
  /** 窗宽 */
  windowWidth: number;
  /** 窗位 */
  windowCenter: number;
}

/**
 * useViewport 返回类型
 */
export interface UseViewportReturn {
  /** 视口ID */
  viewportId: Ref<string | null>;
  /** 是否已创建 */
  isCreated: Ref<boolean>;
  /** 是否正在加载 */
  isLoading: Ref<boolean>;
  /** 当前图像索引 */
  currentImageIndex: Ref<number>;
  /** 图像总数 */
  totalImages: Ref<number>;
  /** 当前窗宽窗位 */
  windowLevel: Ref<WindowLevelSettings | null>;
  /** 错误信息 */
  error: Ref<string | null>;
  /** 是否有上一张图像 */
  hasPrevious: Ref<boolean>;
  /** 是否有下一张图像 */
  hasNext: Ref<boolean>;
  /** 创建视口 */
  createViewport: (elementId: string, config: ViewportConfig) => Promise<void>;
  /** 加载图像到视口 */
  loadImages: (options: ImageLoadOptions) => Promise<void>;
  /** 设置窗宽窗位 */
  setWindowLevel: (windowWidth: number, windowCenter: number) => Promise<void>;
  /** 重置视口 */
  resetViewport: () => Promise<void>;
  /** 渲染视口 */
  render: () => void;
  /** 上一张图像 */
  previousImage: () => Promise<void>;
  /** 下一张图像 */
  nextImage: () => Promise<void>;
  /** 跳转到指定图像 */
  gotoImage: (index: number) => Promise<void>;
  /** 销毁视口 */
  destroyViewport: () => void;
}

/**
 * useViewport - 视口创建和管理
 * 
 * 提供响应式的视口管理，包括图像加载、窗宽窗位调整和图像导航
 * 
 * @param facade - CornerstoneFacade 实例
 * @returns 视口管理方法和状态
 * 
 * @example
 * ```vue
 * <script setup>
 * import { useViewport } from '@/composables/useViewport';
 * import { useCornerstone3D } from '@/composables/useCornerstone3D';
 * 
 * const { facade } = useCornerstone3D();
 * const { 
 *   createViewport, 
 *   loadImages, 
 *   previousImage, 
 *   nextImage 
 * } = useViewport(facade);
 * 
 * onMounted(async () => {
 *   await createViewport('viewport-element', { type: 'STACK' });
 *   await loadImages({ imageIds: ['image1', 'image2'] });
 * });
 * </script>
 * ```
 */
export function useViewport(
  facade: Ref<CornerstoneFacade | null>
): UseViewportReturn {
  // 响应式状态
  const viewportId = ref<string | null>(null);
  const isCreated = ref(false);
  const isLoading = ref(false);
  const currentImageIndex = ref(0);
  const totalImages = ref(0);
  const windowLevel = ref<WindowLevelSettings | null>(null);
  const error = ref<string | null>(null);

  // 存储图像ID列表
  let imageIdsList: string[] = [];

  // 计算属性
  const hasPrevious = computed(() => currentImageIndex.value > 0);
  const hasNext = computed(() => currentImageIndex.value < totalImages.value - 1);

  /**
   * 创建视口
   * 
   * @param elementId - DOM 元素 ID
   * @param config - 视口配置
   */
  const createViewport = async (
    elementId: string,
    config: ViewportConfig
  ): Promise<void> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      isLoading.value = true;
      error.value = null;

      console.log('[useViewport] 创建视口:', elementId, config);
      console.log('[useViewport] facade.value 类型:',  facade.value);
      console.log('[useViewport] facade.value.createViewport 类型:', typeof facade.value.createViewport);
      console.log('[useViewport] facade.value 是否有 createViewport:', 'createViewport' in facade.value);
      console.log('[useViewport] facade.value 的键:', Object.keys(facade.value).slice(0, 10));

      const vp = await facade.value.createViewport({
        elementId,
        viewportId: config.viewportId || `viewport-${Date.now()}`,
        type: config.type,
        background: config.background,
        orientation: config.orientation,
      });

      viewportId.value = vp.id;
      isCreated.value = true;

      console.log('[useViewport] 视口创建成功:', viewportId.value);
    } catch (err: any) {
      console.error('[useViewport] 创建视口失败:', err);
      error.value = err.message || '创建视口失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 加载图像到视口
   * 
   * @param options - 图像加载选项
   */
  const loadImages = async (options: ImageLoadOptions): Promise<void> => {
    if (!facade.value || !viewportId.value) {
      throw new Error('视口未创建');
    }

    try {
      isLoading.value = true;
      error.value = null;

      console.log('[useViewport] 加载图像:', options);

      imageIdsList = options.imageIds;
      totalImages.value = options.imageIds.length;
      currentImageIndex.value = options.currentIndex || 0;

      await facade.value.loadImagesToViewport({
        viewportId: viewportId.value,
        imageIds: options.imageIds,
        currentImageIdIndex: currentImageIndex.value,
      });

      // 如果启用预加载
      if (options.preload) {
        facade.value.preloadImages({
          imageIds: options.imageIds,
          requestType: 'prefetch',
        });
      }

      console.log('[useViewport] 图像加载成功');
    } catch (err: any) {
      console.error('[useViewport] 加载图像失败:', err);
      error.value = err.message || '加载图像失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 设置窗宽窗位
   * 
   * @param windowWidth - 窗宽
   * @param windowCenter - 窗位
   */
  const setWindowLevel = async (
    windowWidth: number,
    windowCenter: number
  ): Promise<void> => {
    if (!facade.value || !viewportId.value) {
      throw new Error('视口未创建');
    }

    try {
      console.log('[useViewport] 设置窗宽窗位:', { windowWidth, windowCenter });

      await facade.value.setWindowLevel({
        viewportId: viewportId.value,
        windowWidth,
        windowCenter,
      });

      windowLevel.value = { windowWidth, windowCenter };
    } catch (err: any) {
      console.error('[useViewport] 设置窗宽窗位失败:', err);
      error.value = err.message || '设置窗宽窗位失败';
      throw err;
    }
  };

  /**
   * 重置视口
   */
  const resetViewport = async (): Promise<void> => {
    if (!facade.value || !viewportId.value) {
      throw new Error('视口未创建');
    }

    try {
      console.log('[useViewport] 重置视口');
      await facade.value.resetViewport(viewportId.value);
      windowLevel.value = null;
    } catch (err: any) {
      console.error('[useViewport] 重置视口失败:', err);
      error.value = err.message || '重置视口失败';
      throw err;
    }
  };

  /**
   * 渲染视口
   */
  const render = (): void => {
    if (!facade.value || !viewportId.value) {
      return;
    }

    try {
      facade.value.renderViewport(viewportId.value);
    } catch (err: any) {
      console.error('[useViewport] 渲染视口失败:', err);
      error.value = err.message || '渲染视口失败';
    }
  };

  /**
   * 上一张图像
   */
  const previousImage = async (): Promise<void> => {
    if (!hasPrevious.value) {
      console.warn('[useViewport] 已经是第一张图像');
      return;
    }

    await gotoImage(currentImageIndex.value - 1);
  };

  /**
   * 下一张图像
   */
  const nextImage = async (): Promise<void> => {
    if (!hasNext.value) {
      console.warn('[useViewport] 已经是最后一张图像');
      return;
    }

    await gotoImage(currentImageIndex.value + 1);
  };

  /**
   * 跳转到指定图像
   * 
   * @param index - 图像索引
   */
  const gotoImage = async (index: number): Promise<void> => {
    if (!facade.value || !viewportId.value) {
      throw new Error('视口未创建');
    }

    if (index < 0 || index >= totalImages.value) {
      throw new Error(`无效的图像索引: ${index}`);
    }

    try {
      console.log('[useViewport] 跳转到图像:', index);
      
      // 这里需要重新加载图像或使用 Cornerstone 的 setImageIdIndex 方法
      // 具体实现取决于 ViewportManager 的 API
      await loadImages({
        imageIds: imageIdsList,
        currentIndex: index,
      });

      currentImageIndex.value = index;
    } catch (err: any) {
      console.error('[useViewport] 跳转图像失败:', err);
      error.value = err.message || '跳转图像失败';
      throw err;
    }
  };

  /**
   * 销毁视口
   */
  const destroyViewport = (): void => {
    if (!facade.value || !viewportId.value) {
      return;
    }

    try {
      console.log('[useViewport] 销毁视口:', viewportId.value);
      // 这里可能需要调用 facade 的清理方法
      viewportId.value = null;
      isCreated.value = false;
      currentImageIndex.value = 0;
      totalImages.value = 0;
      windowLevel.value = null;
      imageIdsList = [];
    } catch (err: any) {
      console.error('[useViewport] 销毁视口失败:', err);
      error.value = err.message || '销毁视口失败';
    }
  };

  return {
    viewportId,
    isCreated,
    isLoading,
    currentImageIndex,
    totalImages,
    windowLevel,
    error,
    hasPrevious,
    hasNext,
    createViewport,
    loadImages,
    setWindowLevel,
    resetViewport,
    render,
    previousImage,
    nextImage,
    gotoImage,
    destroyViewport,
  };
}


